'use strict';
const express = require('express');
const model = require('../../db/model');

const router = express.Router();
const roomRouter = require('./room/router');
const setRouter  = require('./set/router');

router.use('/room', roomRouter);
router.use('/setting', setRouter);

const formatArr = (arr) => {
	if (arr.length == 0) {
		return [];
	}
	let newArr = [];
	let index = 0;
	let floor = arr[0].floor;
	newArr[0] = {
		floorNum: floor,
		roomData: []
	}
	for (let i = 0; i < arr.length; i++) {
		if (floor !== arr[i].floor) {
			index += 1;
			floor = arr[i].floor
			newArr[index] = {
				floorNum: floor,
				roomData: []
			}
		}
		newArr[index].roomData.push(arr[i]);
	}
	return newArr;
}

router.get('/info', function(req, res, next) {
	const sql = `
		select room_state.id,has_card,room_temp,speed,clean,dnd,ask,'leave',roomId,room_name,room_num,floor from room_state,room_info where room_state.roomId=room_info.id order by floor,room_num;
	`;
	model
		.query(sql)
		.then(arr => {
			const list = arr[0];
			res.send({status: true, list: formatArr(arr[0])});
		})
		.catch(err => {
			res.send({status: false, errMsg: err.message});
		})
})

module.exports = router;